package com.canbot.u05.activity.training;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.RectEvaluator;
import android.animation.ValueAnimator;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.glide.GlideApp;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.HashMap;

/**
 * 主持培训模式选择图片界面
 */

public class TrainingChooseImageActivity extends BaseActivityNoTitle implements View.OnClickListener, AdapterView.OnItemClickListener {

        private String[] picPaths;

        private boolean[] bs;

        private int currentPosition;

        private GridView gridView;

        private ToastTools toastTools;

        private ImageView previewIv;

        private Dialog dialogLoading;

        private String oldPath;

        private String oldPicPath;

        private Rect openRect;

        private Rect toRect;

        private boolean isClose;

        private boolean isOpen;

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_training_host_choose_image);
                oldPath = getIntent().getStringExtra("mPicPath");
                oldPicPath = getIntent().getStringExtra("oldPicPath");
                Point outSize = new Point();
                getWindowManager().getDefaultDisplay().getRealSize(outSize);
                toRect = new Rect(0, 0, outSize.x, outSize.y);
                initView();
                initData();
        }

        @Override
        protected void onResume() {
                super.onResume();
        }

        private void initData() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(TrainingChooseImageActivity.this, getResources().getString(R.string.request));
                dialogLoading.show();
                currentPosition = -1;
                myBaseAdapter.notifyDataSetChanged();
                String url = IpMsgConst.HTTP_URL_CHEST + "getAllPic";
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("path", "/uupic");
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                JsonResponse jsonResponse = new Gson().fromJson(result, JsonResponse.class);
                                if (jsonResponse != null) {
                                        dialogLoading.dismiss();
                                        if (jsonResponse.getRc() == -1) {
                                                toastTools.showText(getString(R.string.request_parameter_error));
                                                return;
                                        }
                                        Type type = new TypeToken<String[]>() {
                                        }.getType();
                                        picPaths = new Gson().fromJson(jsonResponse.getResult().toString(), type);
                                        if (picPaths == null || picPaths.length == 0) {
                                                toastTools.showText(getString(R.string.no_images_choose));
                                                return;
                                        }
                                        bs = new boolean[picPaths.length];
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        myBaseAdapter.notifyDataSetChanged();
                                                }
                                        });

                                }
                                else {
                                        toastTools.showText(getString(R.string.network_error));
                                }
                        }

                        @Override
                        public void onFailure() {
                                dialogLoading.dismiss();
                                toastTools.showText(getString(R.string.network_error));
                        }
                });
        }

        private void initView() {

                toastTools = ToastTools.newInstance(this);
                findViewById(R.id.bt_back).setOnClickListener(this);
                findViewById(R.id.bt_close).setOnClickListener(this);

                previewIv = ((ImageView) findViewById(R.id.training_preview_pic_iv));
                previewIv.setOnClickListener(this);

                gridView = (GridView) findViewById(R.id.training_mode_choose_pic_gv);
                gridView.setAdapter(myBaseAdapter);
                gridView.setOnItemClickListener(this);


        }


        @Override
        public void onClick(View v) {
                switch (v.getId()) {
                        case R.id.bt_back:
                                finish();
                                break;
                        case R.id.bt_close:
                                if (currentPosition == -1 && TextUtils.isEmpty(oldPicPath)) {
                                        toastTools.showText(getString(R.string.select_base_map));
                                        return;
                                }
                                Intent intent = new Intent();
                                intent.putExtra("mPicPath", picPaths[currentPosition]);
                                setResult(RESULT_OK, intent);
                                finish();
                                break;
                        case R.id.training_preview_pic_iv:
                                if (isClose) {
                                        return;
                                }
                                close();
                                break;
                }

        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("test", "onItemClick" + position);
                if (isOpen) {
                        return;
                }
                start(((ViewHolder) view.getTag()).trainingImage);
                if (currentPosition != -1) {
                        bs[currentPosition] = false;
                }
                currentPosition = position;
                bs[position] = true;
        }

        private void start(ImageView view) {
                int[] outLocation = new int[2];
                view.getLocationOnScreen(outLocation);
                int width = view.getWidth();
                int height = view.getHeight();
                openRect = new Rect(outLocation[0], outLocation[1], outLocation[0] + width, outLocation[1] + height);
                previewIv.setImageDrawable(view.getDrawable());
                ValueAnimator valueAnimator = ValueAnimator.ofObject(new RectEvaluator(), openRect, toRect)
                                                           .setDuration(1000);
                valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                                Rect value = (Rect) animation.getAnimatedValue();
                                previewIv.layout(value.left, value.top, value.right, value.bottom);
                        }
                });
                valueAnimator.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationCancel(Animator animation) {
                                isClose = false;
                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                                isClose = false;
                        }

                        @Override
                        public void onAnimationStart(Animator animation) {
                                isOpen = true;
                                isClose = true;
                        }
                });
                previewIv.setVisibility(View.VISIBLE);
                valueAnimator.start();
        }

        private void close() {
                ValueAnimator valueAnimator = ValueAnimator.ofObject(new RectEvaluator(), toRect, openRect)
                                                           .setDuration(1000);
                valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                                Rect value = (Rect) animation.getAnimatedValue();
                                previewIv.layout(value.left, value.top, value.right, value.bottom);
                        }
                });
                valueAnimator.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationCancel(Animator animation) {
                                isOpen = false;
                                previewIv.setVisibility(View.INVISIBLE);
                                myBaseAdapter.notifyDataSetChanged();
                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                                isOpen = false;
                                previewIv.setVisibility(View.INVISIBLE);
                                myBaseAdapter.notifyDataSetChanged();
                        }

                        @Override
                        public void onAnimationStart(Animator animation) {
                                isClose = true;
                                isOpen = true;
                        }
                });
                valueAnimator.start();
        }

        BaseAdapter myBaseAdapter = new BaseAdapter() {


                @Override
                public int getCount() {
                        return picPaths == null ? 0 : picPaths.length;
                }

                @Override
                public Object getItem(int position) {
                        return position;
                }

                @Override
                public long getItemId(int position) {
                        return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                        ViewHolder holder;
                        if (convertView == null) {
                                convertView = View.inflate(TrainingChooseImageActivity.this, R.layout.gridview_training_host_image, null);
                                holder = new ViewHolder(convertView);
                                holder.trainingImage = (ImageView) convertView.findViewById(R.id.iv_hint);
                                holder.trainingCheck = (ImageView) convertView.findViewById(R.id.iv_check);
                                holder.trainingCheckbg = (ImageView) convertView.findViewById(R.id.iv_check_bg);
                                holder.textView = (TextView) convertView.findViewById(R.id.tv);
                                convertView.setTag(holder);
                        }
                        else {
                                holder = (ViewHolder) convertView.getTag();
                        }

                        if (picPaths[position].contains("/uupic/")) {
                                holder.textView.setText(picPaths[position].replace("/uupic/", ""));
                        }


                        GlideApp.with(TrainingChooseImageActivity.this).asDrawable()
                                .load(IpMsgConst.HTTP_URL_CHEST + picPaths[position].replace("/uupic/", "/uupic_thumb/"))
                                .thumbnail(0.1f)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                                .skipMemoryCache(false)
                                .placeholder(R.drawable.sales_banner01)//占位图
                                .error(R.drawable.ic_launcher)
                                .into(holder.trainingImage);
                        //                        VolleyUtil.requestImage(IpMsgConst.HTTP_URL_CHEST + picPaths[position], holder.trainingImage, R.drawable
                        // .sales_banner01, R.drawable.sales_banner01);


                        if (picPaths[position].equals(oldPath)) {
                                holder.trainingCheck.setVisibility(View.VISIBLE);
                                holder.trainingCheckbg.setVisibility(View.VISIBLE);
                                oldPath = null;
                        }
                        else if (picPaths[position].equals(oldPicPath)) {
                                holder.trainingCheck.setVisibility(View.VISIBLE);
                                holder.trainingCheckbg.setVisibility(View.VISIBLE);
                                oldPicPath = null;
                        }
                        else if (position == currentPosition) {
                                holder.trainingCheck.setVisibility(View.VISIBLE);
                                holder.trainingCheckbg.setVisibility(View.VISIBLE);
                        }
                        else {
                                holder.trainingCheck.setVisibility(View.INVISIBLE);
                                holder.trainingCheckbg.setVisibility(View.INVISIBLE);
                        }

                        return convertView;
                }
        };

        class ViewHolder {

                private TextView textView;

                private ImageView trainingImage;

                private ImageView trainingCheck;

                private ImageView trainingCheckbg;

                public ViewHolder(View inflate) {
                        textView = (TextView) inflate.findViewById(R.id.tv);
                        trainingImage = (ImageView) inflate.findViewById(R.id.iv_hint);
                        trainingCheck = (ImageView) inflate.findViewById(R.id.iv_check);
                        trainingCheckbg = (ImageView) inflate.findViewById(R.id.iv_check_bg);
                }
        }
}
